package mspbots.next.ticket.core;

import lombok.RequiredArgsConstructor;
import mspbots.next.ticket.common.QueryParams;
import mspbots.next.ticket.core.data.tickets.TicketsServiceImpl;
import mspbots.next.ticket.core.points.PointTicketRegistration;
import mspbots.next.ticket.core.points.ScoringPointAdapter;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;

import java.util.Comparator;

/**
 * mspbots.next.ticket.core.AppServiceImpl
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/12/1
 */
@Service
@RequiredArgsConstructor
public class AppServiceImpl extends AbstractToolsUtil {

    private final TicketsServiceImpl ticketsService;
    private final ScoringPointAdapter scoringPointAdapter;

    public Flux<PointTicketRegistration> grading(Long tenantId, GradingRequest request) {
        return  this.scoringPointAdapter.initializerRules(tenantId,request)
                .flatMapMany(ruleInterceptorRegistrations -> this.ticketsService
                        .fetch(tenantId, QueryParams.withDefault().conditions(request.getConditions()))
                        .publishOn(Schedulers.boundedElastic())
                        .flatMap(ticket -> this.scoringPointAdapter.grading(ruleInterceptorRegistrations, ticket))
                )
                .sort(Comparator.comparing(PointTicketRegistration::getPoint).reversed());
    }
}
